package cn.slipi.core.component.loadbalance;

import cn.slipi.common.enums.LoadBalanceEnum;
import cn.slipi.common.rule.custom.entity.BalancePiece;
import cn.slipi.common.rule.custom.entity.LoadBalance;
import com.google.common.base.Preconditions;
import org.apache.commons.lang3.StringUtils;

/**
 * HashLoadBalanceSelector
 * <p>
 * 获取客户端ip地址，hash后，对server列表进行取模运算
 */
public class HashLoadBalanceSelector implements LoadBalanceSelector {

    @Override
    public BalancePiece select(LoadBalance loadBalance, String ip) {
        Preconditions.checkNotNull(loadBalance);
        Preconditions.checkNotNull(loadBalance.getData());
        final BalancePiece[] balancePieces = loadBalance.getData();
        int length = balancePieces.length;
        if (StringUtils.isBlank(ip) || length == 1) {
            return balancePieces[0];
        }
        int addressHash = ip.hashCode();
        return balancePieces[addressHash % length];
    }

    @Override
    public String getAlgorithm() {
        return LoadBalanceEnum.HASH.getName();
    }
}
